package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.entity.HouseBroker;
import com.atguigu.service.AdminService;
import com.atguigu.service.HouseBrokerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author:ahang
 * @create:2022-07-26 0:59
 * @Description:
 */
@Controller
@RequestMapping("/houseBroker")
public class HouseBrokerController  {

    @Reference
    private AdminService adminService;
    @Reference
    private HouseBrokerService houseBrokerService;
    /**
     * 根据房子id查找房子的经纪人
     * @param houseId
     * @return
     */
    @RequestMapping("/create")
    public String creat( Long houseId, Model model){
        //携带admin列表
        List<Admin> adminList = adminService.findAll();
        model.addAttribute("adminList",adminList);
        //提交需要用到房子id
        model.addAttribute("houseId",houseId);
        return "houseBroker/create";
    }

    @RequestMapping("/save")
    public String save(Long houseId,Long brokerId){//参数列表为房子id和经纪人id

        Admin admin = adminService.getById(brokerId);

        HouseBroker houseBroker = new HouseBroker();
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerId(brokerId);
        houseBroker.setHouseId(houseId);

        houseBrokerService.insert(houseBroker);
        return "common/successPage";
    }

    @RequestMapping("/edit/{id}")//经纪人id
    public String edit(@PathVariable Long id,Model model){
        //携带所有的admin列表
        List<Admin> adminList = adminService.findAll();
        model.addAttribute("adminList",adminList);
        //按照id查询对应的经纪人
        HouseBroker houseBroker = houseBrokerService.getById(id);
        model.addAttribute("houseBroker",houseBroker);

        return "houseBroker/edit";
    }

    @RequestMapping("/update")
    public String update(HouseBroker houseBroker){ //含有id  brokerId
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        //houseBroker.setHouseId(); 和当前操作无关
        //houseBroker.setBrokerId();已经存在
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        //houseBroker.setId();已经存在
        houseBrokerService.update(houseBroker);

        return "common/successPage";
    }
}
